﻿using System.Collections.Generic;
using DotNetNuke.Data;
using System.Data;
using System;
using System.Web.Caching;
using DotNetNuke.Common.Utilities;

namespace CorpGroup.Modules.cgDocuments.Components
{
    class DocumentController
    {
        public Int32 MaxSortNum;
        
        public void CreateDocument(Document doc)
        {
            using (IDataContext ctx = DataContext.Instance())
            {
                var rep = ctx.GetRepository<Document>();
                rep.Insert(doc);
            }                                                          
        }
        
        public void DeleteDocument(int DocumentId, int moduleId)
        {
            var doc = GetDocument(DocumentId, moduleId);
            DeleteDocument(doc);
        }

        public void DeleteDocument(Document doc)
        {
            using (IDataContext ctx = DataContext.Instance())
            {
                var rep = ctx.GetRepository<Document>();
                rep.Delete(doc);
            }
        }

        public IEnumerable<Document> GetDocuments(int moduleId)
        {
            IEnumerable<Document> doc;
            using (IDataContext ctx = DataContext.Instance())
            {
                doc = ctx.ExecuteQuery<Document>(CommandType.Text, "Where ModuleId = @0 order by DocSortOrderId", moduleId);
            }
            MaxSort(moduleId);
            return doc;
        }

        public void MaxSort(int moduleId)
        {
            MaxSortNum = DataProvider.Instance().ExecuteScalar<int>("sp_cgDocuments_Docs_MaxOrder", moduleId);
        }

        public Int32 GetNextSortid(int moduleId)
        {
            MaxSort(moduleId);
            return MaxSortNum + 1;
        }

        public void MoveSortOrder(int sorderid, int moduleid, int changeAmt)
        {
            var tmp = DataProvider.Instance().ExecuteScalar<int>("sp_cgDocuments_Docs_ChangeOrder",
                                                                       sorderid,
                                                                       moduleid,
                                                                       changeAmt);
        }
        
        public Document GetDocument(int DocumentId, int moduleId)
        {
            Document doc;
            using (IDataContext ctx = DataContext.Instance())
            {
                var rep = ctx.GetRepository<Document>();
                doc = rep.GetById(DocumentId, moduleId);
            }
            return doc;
        }

        public void UpdateDocument(Document doc)
        {
            using (IDataContext ctx = DataContext.Instance())
            {
                var rep = ctx.GetRepository<Document>();
                rep.Update(doc);
            }
        }
    }
}